# # -*-coding:utf-8-*-
# # -*- coding: utf-8 -*-
# # @Time    : 2022/10/18 20:58
# # @Author  : gaojy
# # @Site    :
# # @File    : handle_mysql.py
# # @Software: PyCharm
import pymysql

from common.common_function import read_config_yaml


# 从根目录config.yaml获取mysql各项配置信息
class HandleMysql:
    def __init__(self, database = None, charset = 'utf8mb4'):
        # 创建数据库对象
        self.__conn = pymysql.connect(
            host = read_config_yaml("mysql")["host"],
            port = read_config_yaml("mysql")["port"],
            user = read_config_yaml("mysql")["user"],
            password = read_config_yaml("mysql")["password"],
            charset = charset,
            cursorclass = pymysql.cursors.DictCursor,
            database = database
        )
        # 获取游标对象
        self.cursor = self.__conn.cursor()

    # 查询
    def fetch_all(self, sql):
        self.cursor.execute(sql)
        result = self.cursor.fetchall()
        self.cursor.close()
        self.close()
        return result

    # 更新
    def update(self, sql):
        self.cursor.execute(sql)
        self.__conn.commit()
        self.close()
        return

    # 关闭
    def close(self):
        self.cursor.close()
        self.__conn.close()


if __name__ == "__main__":
    pass
